#    This file is part of robo-ircbot.
#
#    robo-ircbot is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    robo-ircbot is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with robo-ircbot.  If not, see <http://www.gnu.org/licenses/>.

package App::Modular::Module::Slashdot;
use strict;
use warnings;
use XML::RSS;
use LWP::Simple;
use base qw(App::Modular::Module);

print ":: Slashdot module loaded.\n";

# Events we want to receive.
sub events { return "PRIVMSG"; }

sub help {
        return (
                "Retrieve the contents of the Slashdot RSS feed.",
                "slashdot [/max=<num>]"
        );
}

# PRIVMSG events.
sub event_privmsg
{
        shift;
        my $e = shift;

        my $help = $e->robo->mod("Helper") || return;

        # Admin commands for slashdot module.
        if ($help->trigger_switch("slashdot", $e)) {
                return;
        }

        # Slashdot trigger.
        if ($e->data =~ /^\.slashdot\s?(\d*)/) {
                my $max = -1;
                if ($1) { $max = $1; }

                read_slashdot($e, $max);
        }
}

# Read the Slashdot RSS feed.
sub read_slashdot
{
        my ($e, $max) = @_;

        # Download the rss content:
        # The get() function downloads any text file from the web
        # and will store it in a variable.
        my $content = get("http://rss.slashdot.org/Slashdot/slashdot");

        # Parse the RSS feed
        my $rss = new XML::RSS;
        $rss->parse($content);

        # Read each item.
        my $count = 1;

        foreach my $item (@{$rss->{items}}) {
                # If a valid max limit has been set, and we have hit that,
                # exit the loop.
                if ($max >= 1 && $max == ($count - 1)) { last; }

                $e->s("PRIVMSG ".$e->dest." :".$count++.") ".
                      $item->{title}." - ".$item->{link});

                # Pause for 1 second as to not get killed for flooding.
                sleep(1);
        }
}

1;
